package com.example.onion.hxchat.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.example.onion.hxchat.room.entity.PictureSet;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author:onion
 */


/**
 * new Thread(){
 *                     public void run(){
 *                         Looper.prepare();
 *                         ImgDownUtil imgDownUtil = new ImgDownUtil();
 *                         //netImgStr = getImgFromServer(getLocalMac());
 *                         netImgStr = imgDownUtil.getImgFromServer(getLocalMac());
 *                         Log.i("inputstream",netImgStr);
 *                         //Bundle mBundle = getBundleFromStr(netImgStr);
 *                         Bundle mBundle = imgDownUtil.getBundleFromStr(netImgStr);
 *
 *                         //获取图片信息，并将其转换成byte[]
 *                         List<PictureSet> imgList = (ArrayList)(mBundle.getStringArrayList("retResult"));
 *                         byte[] data = null;
 *                         List<byte[]> byteList = new ArrayList<byte[]>();
 *                         for(int j=0;j<imgList.size();j++){
 *                             data = imgDownUtil.getImg(imgList.get(j).pictureData);
 *                             byteList.add(data);
 *                             mBundle.putByteArray("imgPath" + j, data);
 *                         }
 *
 *                         Message msg = new Message();
 *                         msg.setData(mBundle);
 *                         obtainHandler.sendMessage(msg);
 *                     }
 *                 }.start();
 */
public class ImgDownUtil {



    /**
     * 下载图片bytes
     * @param url
     * @return byte[]
     * @throws IOException
     */
    public static byte[] getImageBytes(String url) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        return response.body().bytes();
    }

    /**
     * 将byte转换成bitmap
     * @param b
     * @return
     */
    public static Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }


//    private final static String reqeustURL  = "http://103.8.220.166:40000/lechu/device/image/filedownload";
//    private final static String ALBUM_PATH = Environment.getExternalStorageDirectory()+"/download_img/";
//    private Bundle bundle;
//
//
//    /**
//     * 下载图片
//     * @param url
//     * @param imagePath 图片路径
//     * @return byte[]
//     * @throws IOException
//     */
//    public static byte[] downloadImage(String url, String imagePath) throws IOException {
//        OkHttpClient okHttpClient = new OkHttpClient();
//        Request request = new Request.Builder()
//                .url(url+"/show?fileName="+imagePath)
//                .build();
//        Response response = okHttpClient.newCall(request).execute();
//        byte[] bytes = response.body().bytes();
//        return bytes;
//    }
//
//    /**
//     * 上传图片
//     * @param url
//     * @param imagePath 图片路径
//     * @return 新图片的路径
//     * @throws IOException
//     * @throws JSONException
//     */
//    public static String uploadImage(String url, String imagePath) throws IOException, JSONException {
//        OkHttpClient okHttpClient = new OkHttpClient();
//        Log.d("imagePath", imagePath);
//        File file = new File(imagePath);
//        RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);
//        RequestBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                .addFormDataPart("file", imagePath, image)
//                .build();
//        Request request = new Request.Builder()
//                .url(url+"/uploadImage")
//                .post(requestBody)
//                .build();
//        Response response = okHttpClient.newCall(request).execute();
//        JSONObject jsonObject = new JSONObject(response.body().string());
//        return jsonObject.optString("image");
//    }
//
//    public ImgDownUtil(){
//
//    }
//
//    //从服务器上获取响应数据
//    public String getImgFromServer(String mac){
//        HttpClient client = new DefaultHttpClient();
//        HttpGet httpGet = new HttpGet(reqeustURL+"/"+mac+"/");
//        String imgStream = null;
//        try{
//            HttpResponse hresponse = client.execute(httpGet);
//            HttpEntity entity = hresponse.getEntity();
//            imgStream = EntityUtils.toString(entity);
////            is = entity.getContent();
//        }catch (Exception ex){
//            ex.printStackTrace();
//        }
//        return imgStream;
//    }
//
//    //将从服务器上获取的字符串转化成Bundle
//    public Bundle getBundleFromStr(String str){
//        try{
//            JSONObject jsonObject = new JSONObject(str);
//            bundle = new Bundle();
//            bundle.putString("retCode",jsonObject.getString("retCode").toString());
//            bundle.putString("retInfo",jsonObject.getString("retInfo").toString());
//            //JSONObject subObject = new JSONObject(jsonObject.getString("retResult"));
//            String jsonStr = jsonObject.getString("retResult");
////            String str = jsonStr.substring(1).replace("]", "");
//            JSONArray jsonArr = new JSONArray(jsonStr);
//
//            List<PictureSet> psList = new ArrayList<PictureSet>();
//            for(int i=0;i<jsonArr.length();i++){
//                JSONObject subObject = new JSONObject(jsonArr.get(i).toString());
//                PictureSet ps = new PictureSet();
//                ps.cameraId = subObject.getInt("cameraId");
//                ps.pictureName = subObject.getString("pictureName");
//                ps.createTime = subObject.getString("createTime");
//                ps.pictureData = subObject.getString("pictureData");
//                psList.add(ps);
//                Log.i("subObject", jsonArr.get(i).toString());
//            }
//            bundle.putStringArrayList("retResult", (ArrayList) psList);
//        }catch (Exception ex){
//            ex.printStackTrace();
//        }
//        return bundle;
//    }
//
//    //获取图片
//    public byte[] getImg(String imgPath){
//        try{
//            URL url = new URL(imgPath);
//            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//            conn.setConnectTimeout(5*1000);
//            conn.setRequestMethod("GET");
//            InputStream is = conn.getInputStream();
//            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
//                return readStream(is);
//            }
//        }catch (MalformedURLException mue){
//            //URL抛出的异常
//            mue.printStackTrace();
//        }catch (IOException ie){
//            //HttpURLConnection抛出的异常。
//            ie.printStackTrace();
//        }
//        return null;
//    }
//    //将图片流转化为数据
//    public static byte[] readStream(InputStream inputStream){
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        byte[] buffer = new byte[1024];
//        int len =0;
//        try{
//            while ((len = inputStream.read(buffer))!=-1){
//                byteArrayOutputStream.write(buffer,0,len);
//            }
//            byteArrayOutputStream.close();
//            inputStream.close();
//        }catch (Exception ex){
//            ex.printStackTrace();
//        }
//        return byteArrayOutputStream.toByteArray();
//    }
//
//
//    //保存图片到本地
//    public void saveFile(Bitmap bm, String imgName){
//        File dirFile = new File(ALBUM_PATH);
//        if(!dirFile.exists()){
//            dirFile.mkdir();
//        }
//
//        File myFile = new File(ALBUM_PATH+imgName);
//        try{
//            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myFile));
//            bm.compress(Bitmap.CompressFormat.JPEG,80,bos);
//            bos.flush();
//            bos.close();
//        }catch (Exception ex){
//            ex.printStackTrace();
//        }
//
//    }
}
